// by Jens Schmidt 2009
// for: YOU
// use, modify, copy this as you like

var LocrComms = Class.create({
	busy:false,
	locrSig:0,
	loginvalidated:false,
	username:'',
	password:'',
	parentCallBack:0,
	
	initialize: function() {
		this.successFn=this.success.bind(this);
		this.failureFn=this.failure.bind(this);
	},
	
	setLogin : function(param){
			if (param.username) {
				this.username = param.username;
			}
			if (param.pass) {
				this.password = param.pass;
			}
		},
	
	getLocr: function(param){
		//this.callbackcount=0;
		if (param) {
			this.busy=true;
			var nothingChanged=this.loginvalidated; // means login credentials did not change
			if (param.what) {
				this.task = param.what;
			}
			if (param.username) {
				nothingChanged = nothingChanged && (this.username==param.username);
				this.username = param.username;
			}
			if (param.pass) {
				nothingChanged = nothingChanged && (this.password==param.pass);
				this.password = param.pass;
			}
			
			if (nothingChanged && this.task==LocrComms.validateLogin ){
				// no need to check
				this.finished('ready');
				return;
			}
			
			this.filename=param.filename;
			this.caption=param.caption;
			this.description=param.description;
			this.privacy=param.privacy;
			this.parentCallBack=param.callback;
		}
		
		if (!(this.username && this.password)){
			Mojo.Controller.errorDialog('Check the account settings in the preferences.')
			this.finished('try again, after setting account details');
			return;
		}
									
		var params = new Hash();
		var url;
		
		if (this.locrSig){
		
			switch (this.task) {
				case 'accountDetails':
					url = 'http://de.locr.com/api/get_account_json.php';
					break;
				
				case 'upload':
		 			var url='http://de.locr.com/api/post_photo_json.php';
		 			break;			
			}
			
			var auth_token = Md5.MD5(this.password + this.locrSig);
		
			if (this.task==LocrComms.uploadCommand){
				// using Palm download manager instead of Ajax
				
				// encode authorisation in the url
				url=url+'?auth_user_name='+this.username;
		 		url=url+'&api_signature='+this.locrSig;
		 		url=url+'&auth_token='+auth_token;
	 		
		 		// also encode user entered details in the url
				if (this.caption) {
					url = url + '&caption=' + encodeURIComponent(this.caption);
				}
				if (this.description) {
					url = url + '&description=' + encodeURIComponent(this.description)
				}
		 		url=url+'&privacy='+encodeURIComponent(this.privacy);
		 		
		 		// also let locr convert the image in the background
		 		url=url+'&photo_conv_bg=true';
				
				this.request=new Mojo.Service.Request('palm://com.palm.downloadmanager/', {
			 		method: 'upload',
			 		parameters: {
			 			'fileName': this.filename,
			 			'fileLabel': 'file',
			 			'url': url,
			 			'contentType': 'img',
			 			subscribe: true
			 		},
			 		onSuccess: this.successFn,
					onFailure: this.failureFn
		 		});
				//this.filename=0;
				return;
			}
			
			params.set('auth_user_name', this.username);
			params.set('api_signature', this.locrSig);
			params.set('auth_token', auth_token);
		}else{
			// must get the API signature (and create auth token) first
			url = 'http://www.locr.com/api/get_api_signature.php';
		}
		
		this.request=new Ajax.Request(url, {
			method: "get",
			parameters: params,
			evalJSON: "false",
			onSuccess: this.successFn,
			onFailure: this.failureFn
		});
		delete params;
	},

	failure : function(transport){
		this.filename=0;
		if (transport.errorText){
			if (transport.errorText == 'com.palm.downloadmanager is not running.') {
				this.finished('not supported / OS update required');
			}else{
				this.finished(transport.errorText);//'try again later');
			}
		}
		else {
			this.finished('retry later');//, transport);
		}
	},

	success : function(transport){
		// locr gave us something back
		if (this.locrSig){
			
			var json;
			
			if (this.task=='upload'){
				// palm dowload manager returns directly what we want
				json = transport;
			}else{
				// AJAX retruns what we want in the response text
				if (transport.responseText) {
					json = transport.responseText.evalJSON();
				}
			}
		
			if (json){
				switch (this.task) {
					case 'accountDetails':
							this.finished('checked login ('+json.status+')');//,transport);
							if (json.status=='ok'){
								this.loginvalidated=true;
							}else{
								this.loginvalidated=false;
								this.username = 0;
								this.password = 0;
							}
							break;
							
					case 'upload':
						if (json.responseString) {
							this.filename=0;
							// palm download manager only returns a "responseString" property
							// when the upload finished
							json = json.responseString.evalJSON();
							if (json.status) {
								if (json.status=='ok'){
									this.finished('uploaded');
									this.loginvalidated=true;
								}else{
									this.finished(json.responseString);//'not uploaded - try again later');
								}
							}
							else{
								this.finished('try again later');//,transport);

							}
						}
						else {
							// still busy uploading
							if (this.parentCallBack) {
								//++this.callbackcount;
								var uploadtxt='uploading '+this.filename;//+' '+this.callbackcount;
								this.parentCallBack({
									type: LocrComms.notificationType,
									txt: uploadtxt
								});
							}
						}
						break;
				}
			}else{
				// no json
				// this is an edge case
				this.finished('try again later');//,transport);
			}
		}else{
			// just received the locr API signature, now trigger the real API call
			this.locrSig = transport.responseText;
			this.getLocr();
		}
	},
	
	finished : function(status){//,transport){
		this.busy=false;
		this.locrSig=0;
		if (this.parentCallBack) {
				this.parentCallBack({
					type: LocrComms.notificationType,
					txt: status,
			//		transport: transport,
					finished: true
				});
		}
	}
})

LocrComms.uploadCommand='upload';
LocrComms.validateLogin='accountDetails';
LocrComms.notificationType='locrUpdate';